package com.dbh.company.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.lang.UUID;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.HttpMethod;
import com.amazonaws.SdkClientException;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.*;
import org.apache.http.entity.ContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;

/**
 * @author dongbanghui
 * @create 2023/9/12
 */
public class S3Util {

    private static final Logger LOGGER = LoggerFactory.getLogger(S3Util.class);

    private static String endpoint = "http://storage.lianjia.com";

    private static String ak = "21YK0FVIQ5PPUDHTXTEP";
    private static String sk = "qZP2rT3qeWQ6pqrCSk4VER+FBF78l/2VP8u+aLFh";

    public static String generateUrl(String bucket, String key) {
        AwsClientBuilder.EndpointConfiguration endpointConfiguration =
                new AwsClientBuilder.EndpointConfiguration(endpoint, "cn-north-1");//只有外网才有预签名
        BasicAWSCredentials awsCreds = new BasicAWSCredentials(ak, sk);
        AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
                .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
                .withEndpointConfiguration(endpointConfiguration)
                .withPathStyleAccessEnabled(true)
                .build();
        // Set the presigned URL to expire after one hour.
        Date expiration = new java.util.Date();
        long expTimeMillis = expiration.getTime();
        expTimeMillis += 1000 * 60 * 600;
        expiration.setTime(expTimeMillis);

        // Generate the presigned URL.
        System.out.println("Generating pre-signed URL.");
        GeneratePresignedUrlRequest generatePresignedUrlRequest =
                new GeneratePresignedUrlRequest(bucket, key)
                        .withMethod(HttpMethod.GET)
                        .withExpiration(expiration);
        generatePresignedUrlRequest.withSdkRequestTimeout(1000);

        generatePresignedUrlRequest.withSdkClientExecutionTimeout(1000);
        URL url = s3Client.generatePresignedUrl(generatePresignedUrlRequest);
        S3Object object = s3Client.getObject(bucket, key);
        System.out.println("-------"+ JSONObject.toJSON(object));
        int t1 = generatePresignedUrlRequest.getSdkRequestTimeout();
        int t2 = generatePresignedUrlRequest.getSdkClientExecutionTimeout();
        System.out.println(t1+"  "+t2);
        String returnUrl = url.toString();
        return returnUrl;
    }

    public static void upload(String bucket, String key, byte[] buffer, String contentType) {
        AwsClientBuilder.EndpointConfiguration endpointConfiguration = new AwsClientBuilder.EndpointConfiguration(endpoint, "cn-north-1");

        try {
            BasicAWSCredentials awsCreds = new BasicAWSCredentials(ak, sk);

            AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
                    .withPathStyleAccessEnabled(true)
                    .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
                    .withEndpointConfiguration(endpointConfiguration)
                    .build();

            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType(contentType);//文件的content-type
            metadata.setContentLength(buffer.length);
            InputStream is = new ByteArrayInputStream(buffer);

            PutObjectRequest request = new PutObjectRequest(bucket, key, is, metadata);

            request.setMetadata(metadata);
            PutObjectResult putObjectResult = s3Client.putObject(request);
           Console.log("上传成功,bucket--{}, key:{}", bucket, key);
//            GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(bucket, key);
//            URL url = s3Client.generatePresignedUrl(urlRequest);
//            System.out.println(url.toString());
        } catch (AmazonServiceException e) {
            e.printStackTrace();
        } catch (SdkClientException e) {
            e.printStackTrace();
        }
    }

    public static String upload(String bucket, String key, String filePath, String contentType) {
        AwsClientBuilder.EndpointConfiguration endpointConfiguration = new AwsClientBuilder.EndpointConfiguration(endpoint, "cn-north-1");

        try {
            BasicAWSCredentials awsCreds = new BasicAWSCredentials(ak, sk);

            AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
                    .withPathStyleAccessEnabled(true)
                    .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
                    .withEndpointConfiguration(endpointConfiguration)
                    .build();

            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType(contentType);//文件的content-type
            PutObjectRequest request = new PutObjectRequest(bucket, key, new File(filePath));
            request.setMetadata(metadata);
            s3Client.putObject(request);
            Console.log(key);
            return key;
//            GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(bucket, key);
//            URL url = s3Client.generatePresignedUrl(urlRequest);
//            System.out.println(url.toString());
        } catch (AmazonServiceException e) {
            e.printStackTrace();
        } catch (SdkClientException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * s3删除文件
     * @param bucketName
     * @param key
     */
    public static void delete(String bucketName, String key) {
        AwsClientBuilder.EndpointConfiguration endpointConfiguration = new AwsClientBuilder.EndpointConfiguration(endpoint, "cn-north-1");
        try {
            BasicAWSCredentials awsCreeds = new BasicAWSCredentials(ak, sk);
            AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
                    .withPathStyleAccessEnabled(true)
                    .withCredentials(new AWSStaticCredentialsProvider(awsCreeds))
                    .withEndpointConfiguration(endpointConfiguration)
                    .build();
            s3Client.deleteObject(bucketName, key);
            Console.log("数据已物理删除,结果成功,bucket:{}, key:{}", bucketName, key);

        } catch (AmazonServiceException e) {
            LOGGER.error("AmazonServiceException : ", e);
        } catch (SdkClientException e) {
            LOGGER.error("SdkClientException : ", e);
        }
    }

    public static String copy(String sourceBucketName, String sourceKey,
                              String destinationBucketName, String destinationKey) {
        return "https://img.ljcdn.com/" + sourceBucketName + "/" + sourceKey;

//        AwsClientBuilder.EndpointConfiguration endpointConfiguration = new AwsClientBuilder.EndpointConfiguration(endpoint, "cn-north-1");
//        BasicAWSCredentials awsCreds = new BasicAWSCredentials(ak, sk);
//        AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
//                .withPathStyleAccessEnabled(true)
//                .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
//                .withEndpointConfiguration(endpointConfiguration)
//                .build();
//        CopyObjectResult copyObjectResult = s3Client.copyObject(sourceBucketName, sourceKey, destinationBucketName, destinationKey);
//        if (copyObjectResult != null) {
//            return copyObjectResult.getETag();
//        }
//        return null;
    }



    public static void main(String[] args) throws MalformedURLException {
//        String s = generateUrl("element-library", "prod-da287f8a-5406-4471-a7e9-e11f31a332d5.png");
//        System.out.println(s);
//        for (int i =8; i <= 16; i++) {
//           upload("element-library", "test-" + UUID.randomUUID() + ".png", "D:\\data\\work\\file\\楼书\\楼书1.0\\gif图\\底图\\240119日照\\"+i+".png", "image/png");
//        }


        byte[] bytes = FileUtil.readBytes("D:\\data0\\output_scaled.png");
        upload("element-library", "prod-" + UUID.randomUUID() + ".jpg", bytes, "image/jpeg");

//       upload("element-library", "prod-7163973d-56c4-4337-be9d-9d88a4f1lou07f0f.json", "D:\\data\\workspace\\code\\sun_rise\\winter_solar_position_suzhou.json", "application/json");

//
//        String key = upload("hdic-3d", "prod-" + UUID.randomUUID() + ".max", "D:\\data\\Downloads\\昆明一年日照动画43帧.max", ContentType.APPLICATION_OCTET_STREAM.getMimeType());
//        System.out.println(key);

//        String cityStr = "huizhou";
//        List<String> seasonList = new ArrayList<>();
//        seasonList.add("spring");
//        seasonList.add("summer");
//        seasonList.add("autumn");
//        seasonList.add("winter");
//        Map<String, String> map = new HashMap<>();
//        for (String season : seasonList) {
//            String filePath = "D:\\data\\workspace\\code\\sun_rise\\" + season + "_solar_position_" + cityStr + ".json";
//            String key = upload("element-library", "prod-" + UUID.randomUUID() + ".json", filePath, "application/json");
//            map.put(season, key);
//        }
//
//        System.out.println(JSONUtil.toJsonStr(map));

    }


}

